package com.leyou.cart.controller;

import com.leyou.cart.pojo.Cart;
import com.leyou.item.pojo.Sku;
import com.leyou.cart.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class CartController {

    @Autowired
    private CartService cartService;

    @GetMapping("selectedSkus")
    public ResponseEntity<List<Sku>> querySkusByids(@RequestParam("idds")List<Long> ids){
        List<Sku> skus = cartService.querySkusByids(ids);
        if (CollectionUtils.isEmpty(skus)){
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(skus);
    }

    /**
     * 添加购物车到Redis业务
     * @param cart
     * @return
     */
    @PostMapping("addCarts")
    public ResponseEntity<Void> addCartsToRedis(@RequestBody Cart cart){
        System.out.println(cart.getNum());
        cartService.addCartsToRedis(cart);
        return ResponseEntity.ok().build();
    }

    /**
     * 查询当前用户的购物车信息
     * @return
     */
    @GetMapping("getCartsOfUser")
    public ResponseEntity<List<Cart>> queryCartsOfCurrentUser(){
        List<Cart> carts = cartService.queryCartsOfCurrentUser();
        if (CollectionUtils.isEmpty(carts)){
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(carts);
    }

    /**
     * 更改购物车商品的数量，对应更改Redis中的数据
     * @param skuId
     * @param num
     * @return
     */
    @PutMapping("updateCartNum")
    public ResponseEntity<Void> updateCartNumOfCurrentUser(
            @RequestParam("skuId")Long skuId,
            @RequestParam("num")Integer num
    ){
        cartService.updateCartNumOfCurrentUser(skuId,num);
        return ResponseEntity.ok().build();
    }

    /**
     * 用户登录后删除购物车操作
     * @param skuId
     * @return
     */
    @DeleteMapping("deleteCartOfUser")
    public ResponseEntity<Void> deleteCartOfCurrentUser(@RequestParam("skuId")Long skuId){

        cartService.deleteCartOfCurrentUser(skuId);
        return ResponseEntity.ok().build();
    }

    @PostMapping("addLocalcarts")
    public ResponseEntity<List<Cart>> addLocalStorageCartsToRedisAndQuery(@RequestBody List<Cart> localCarts){
        List<Cart> carts = cartService.addLocalStorageCartsToRedisAndQuery(localCarts);
        if (CollectionUtils.isEmpty(carts)){
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(carts);
    }

    @PostMapping("transferToCollect")
    public ResponseEntity<Void> transferCartToCollect(@RequestParam("skuId")Long skuId){
        cartService.transferCartToCollect(skuId);
        return ResponseEntity.ok().build();
    }


}
